<?php

namespace app\service;

use app\model\Dept;
use app\model\User;
use app\validate\DeptValidate;
use think\annotation\Inject;
use think\exception\ValidateException;

class DeptService
{
    /**
     * @Inject()
     * @var Dept
     */
    protected $deptModel;

    /**
     * @Inject()
     * @var User
     */
    protected $userModel;

    public function getDeptList()
    {
        $res = $this->deptModel->getDeptList();
        if ($res['code'] != 0) {
            return $res;
        }

        return dataReturn(0, 'success', makeMenuTree($res['data']->toArray(), 'pid'));
    }

    public function getSelectDeptList()
    {
        $res = $this->deptModel->getAllList(['status' => 1], 'id value,id,name label,pid', 'id asc');
        if ($res['code'] != 0) {
            return $res;
        }

        return dataReturn(0, 'success', makeMenuTree($res['data']->toArray(), 'pid'));
    }

    public function addDept($param)
    {
        try {

            validate(DeptValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-5, $e->getError());
        }

        return $this->deptModel->addDept($param);
    }

    public function editDept($param)
    {
        try {

            validate(DeptValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-5, $e->getError());
        }

        if ($param['status'] == 2) {
            $has = $this->userModel->getUserByDeptId($param['id']);
            if (!empty($has)) {
                return dataReturn(-6, '该部门下有用户，无法禁用。');
            }
        }

        return $this->deptModel->editDept($param);
    }

    public function delDept($deptId)
    {
        $has = $this->userModel->getUserByDeptId($deptId);
        if (!empty($has['data']->toArray())) {
            return dataReturn(-6, '该部门下有用户，不可删除。');
        }

        $has = $this->deptModel->getSubDept($deptId);
        if (!empty($has['data'])) {
            return dataReturn(-7, '该部门下有子部门，不可删除。');
        }

        return $this->deptModel->delDeptById($deptId);
    }
}